from global_vars import VARS
from cqhttp import CQHttp
from util import print_log
from register import message_listener
from util import print_log
import time
import importlib
import global_vars
config = global_vars.CONFIG[__name__]
water_last: dict = None
water_cnt: dict = None


def plugin():
    return {
        "author": "0xis",
        "version": 1.0,
        "description": "淼群计数器"
    }


def load():
    global water_last, water_cnt
    VARS["water_last"] = dict()
    VARS["water_cnt"] = dict()
    water_last = VARS["water_last"]
    water_cnt = VARS["water_cnt"]

def water_update(group, user_id):
    now_week = time.strftime("%W")
    if group not in water_last:
        water_last[group] = { user_id: time.time() }
        water_cnt[group] = { user_id: 0 }
    elif user_id not in water_last[group]:
        water_last[group][user_id] = time.time()
        water_cnt[group][user_id] = 0
    elif water_last[group][user_id] != now_week:
        water_last[group][user_id] = now_week
        water_cnt[group][user_id] = 0

@message_listener
def water_handler(bot: CQHttp, context, message):
    global water_last, water_cnt
    group = context["group_id"]
    user_id = context["sender"]["user_id"]
    water_update(group, user_id)
    water_cnt[group][user_id] += 1

@command(name="H2O", help="查看水群次数")
def water_group(bot, context, args):
    global water_last, water_cnt
    group = context["group_id"]
    user_id = context["sender"]["user_id"]
    nickname = context["sender"]["nickname"]
    water_update(group, user_id)
    message = "%s 本周水了 %d 次群。" % (nickname, water_cnt[group][user_id])
    bot.sent(context, message)


